package com.example.hospital.service;

import com.example.hospital.common.PageResponse;
import com.example.hospital.domain.dto.ChangePasswordRequest;
import com.example.hospital.domain.dto.RegisterRequest;
import com.example.hospital.domain.entity.ExaminationOrder;
import com.example.hospital.domain.entity.User;
import com.example.hospital.mapper.ExaminationOrderMapper;
import com.example.hospital.mapper.IndicatorResultMapper;
import com.example.hospital.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserMapper userMapper;
    private final ExaminationOrderMapper orderMapper;
    private final IndicatorResultMapper indicatorResultMapper;

    public UserService(UserMapper userMapper, ExaminationOrderMapper orderMapper, IndicatorResultMapper indicatorResultMapper) {
        this.userMapper = userMapper;

        this.orderMapper = orderMapper;

        this.indicatorResultMapper = indicatorResultMapper;
    }

    /**
     * 注册用户
     * @param req
     * @return
     */
    public User register(RegisterRequest req) {
        User exists = userMapper.findByUsername(req.getUsername());
        if (exists != null) throw new IllegalArgumentException("用户名已存在");
        User user = new User();
        user.setUsername(req.getUsername());
        // 明文存储（按当前需求），后续可改为哈希
        user.setPassword(req.getPassword());
        user.setName(req.getName());
        user.setGender(req.getGender());
        user.setAge(req.getAge());
        user.setPhone(req.getPhone());
        user.setIdCard(req.getIdCard());
        userMapper.insert(user);
        return userMapper.findById(user.getUserId());
    }
    /**
     * 用户登录
     * @param username
     * @param password
     * @param phone
     * @return
     */
    public User login(String username, String password, String phone) {
        User user = null;
        if (username != null && !username.isEmpty()) {
            user = userMapper.findByUsername(username);
        }
        if (user == null && phone != null && !phone.isEmpty()) {
            user = userMapper.findByPhone(phone);
        }
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 明文校验
        if (!password.equals(user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }
        return user;
    }
    /**
     * 用户修改密码
     * @param req
     * @return
     */
    public boolean changePassword(ChangePasswordRequest req) {
        User user = userMapper.findById(req.getUserId());
        if (user == null) throw new IllegalArgumentException("用户不存在");
        if (!req.getOldPassword().equals(user.getPassword())) {
            throw new IllegalArgumentException("旧密码不正确");
        }
        return userMapper.updatePassword(req.getUserId(), req.getNewPassword()) > 0;
    }
    /**
     * 获取用户个人信息
     * @param userId
     * @return
     */
    public User getProfile(Long userId) {
        return userMapper.findById(userId);
    }
    /**
     * 更新用户个人信息
     * @param user
     * @return
     */
    public boolean updateProfile(User user) {
        return userMapper.updateProfile(user) > 0;
    }
    /**
     * 创建订单
     * @param order
     * @return
     */
    public ExaminationOrder createOrder(ExaminationOrder order) {
        if (order.getOrderType() == null) throw new RuntimeException("订单类型必填");
        if ("PACKAGE".equals(order.getOrderType())) {
            if (order.getPackageId() == null) throw new RuntimeException("套餐ID必填");
            order.setIndicatorId(null);
        } else if ("INDICATOR".equals(order.getOrderType())) {
            if (order.getIndicatorId() == null) throw new RuntimeException("项目ID必填");
            order.setPackageId(null);
        } else {
            throw new RuntimeException("订单类型无效");
        }
        order.setStatus(1); // 待确认
        orderMapper.insert(order);
        return orderMapper.findById(order.getOrderId());
    }
    /**
     * 获取用户订单列表
     * @param userId
     * @param status
     * @param orderType
     * @param page
     * @param size
     * @return
     */
    public PageResponse<ExaminationOrder> listOrders(Long userId, Integer status, String orderType, int page, int size) {
        int offset = (page - 1) * size;
        List<ExaminationOrder> list = orderMapper.list(userId, null, status, orderType, size, offset);
        long total = orderMapper.count(userId, null, status, orderType);
        return PageResponse.of(total, page, size, list);
    }

    /**
     * 获取用户订单下的指标结果列表
     * @param userId
     * @param orderId
     * @param page
     * @param size
     * @return
     */
    public PageResponse<com.example.hospital.domain.entity.IndicatorResult> listMyIndicatorResults(Long userId, Long orderId, int page, int size) {
        int offset = (page - 1) * size;
        List<com.example.hospital.domain.entity.IndicatorResult> list = indicatorResultMapper.listByUserOrOrder(userId, orderId, size, offset);
        long total = indicatorResultMapper.countByUserOrOrder(userId, orderId);
        return PageResponse.of(total, page, size, list);
    }
}